﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using RHD.Common.Web.Components.Button;
using RHD.Web.Infrastructure;

namespace RHD.Common.Web.Components {
	public static class ButtonExtension {
		public static MvcHtmlString Button(this HtmlHelper htmlHelper, string id, string title, Action<ButtonBuilder> optionsHandle = null, object htmlAttributes = null) {
			ButtonBuilder options = new ButtonBuilder();
			if (optionsHandle != null)
				optionsHandle(options);

			TagBuilder button = new TagBuilder("button");
			button.GenerateId(id);
			button.AddCssClass(string.Format("btn btn-{0}", options.type.ToString().ToLower()));
			button.Attributes["title"] = options.tooltip;
			button.SetInnerText(title);
			if (htmlAttributes != null)
				button.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));
			id = button.Attributes["id"];

			if (!string.IsNullOrEmpty(options.icon)) {
				TagBuilder icon = new TagBuilder("span");
				icon.AddCssClass(options.icon);
				button.InnerHtml = icon.ToString() + " " + button.InnerHtml;
			}

			RegisterScript(htmlHelper, id, options);
			return MvcHtmlString.Create(button.ToString());
		}

		private static void RegisterScript(HtmlHelper htmlHelper, string id, ButtonBuilder options) {
			string fnOnClick = string.Empty;
			if (!string.IsNullOrEmpty(options.urlAction)) {
				fnOnClick = string.Format("window.location = '{0}';", options.urlAction);
			} else if (!string.IsNullOrEmpty(options.function)) {
				fnOnClick = options.function;
			} else {
				string form = !string.IsNullOrEmpty(options.form) ? string.Format("$(\"#{0}\")", options.form) : "$(this).parents('form')";
				fnOnClick = string.Format("var form = {0}; if (form.length == 0) return; if(form.valid()) form.submit();", form);
			}

			string script = string.Format("$(\"#{0}\").click(function(){{ {1} }});", id, fnOnClick);
			htmlHelper.AddScript(script);
		}
	}
}